//
//  SearchGrpMemberViewController.m
//  SouthChina
//
//  Created by kc on 15/8/9.
//  Copyright (c) 2015年 科创. All rights reserved.
//

#import "SearchGrpMemberViewController.h"
#import "UnitView.h"
#import "ContactDao.h"
#import "selectMemberTableViewCell.h"
#import "selectTableViewController.h"
#import "GroupInfoViewController.h"
#import "selectMemberViewController.h"
#import "CreateGroupViewController.h"
@interface SearchGrpMemberViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>
{
    NSMutableArray *searchArr; //搜索列表
    UITextField *searchField;
}
@property (strong, nonatomic) IBOutlet UISearchBar *searchgrpmeber;
@property (strong, nonatomic) IBOutlet UITableView *tablegrpmember;
@property (strong, nonatomic) IBOutlet UnitView *grpMemberList;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *listbottom;

@end

@implementation SearchGrpMemberViewController
@synthesize selectedContact,CreateType;
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    _tablegrpmember.delegate = self;
    _tablegrpmember.dataSource = self;
    _tablegrpmember.bounces = YES;
    
    //ios7.0 之后UISearchBar 结构发生了变化
    if ([[[UIDevice currentDevice] systemVersion] floatValue]<7.0)
        searchField=[_searchgrpmeber.subviews objectAtIndex:1];
    else
        searchField=[((UIView *)[_searchgrpmeber.subviews objectAtIndex:0]).subviews lastObject];
    [searchField setReturnKeyType:UIReturnKeyDone];
    
    _searchgrpmeber.delegate = self;
    _searchgrpmeber.placeholder = @"输入用户名或群组名搜索";
    _searchgrpmeber.showsCancelButton=NO;
    _searchgrpmeber.barStyle=UIBarStyleDefault;
    _searchgrpmeber.keyboardType = UIKeyboardTypeDefault;
    
    _grpMemberList.isDoneButton = YES;
    _grpMemberList = [_grpMemberList initWithFrame:_grpMemberList.frame];
    _grpMemberList.delegate = self;
    
    for( Contact * contact in selectedContact)
    {
        [_grpMemberList addNewUnit:contact];
    }
    [self searchGroupList:@""];
    [_tablegrpmember reloadData];
    // Do any additional setup after loading the view from its nib.
}

-(void)viewDidUnload
{
    [super viewDidUnload];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification
                                                  object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification
                                                  object:nil];
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    
    NSLog(@"shouldBeginEditing");
    return YES;
    
}

# pragma mark Keyboard Notifications

- (void)keyboardWillShow:(NSNotification *)notification {
    NSDictionary *userInfo = [notification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    int height = keyboardRect.size.height;
    _listbottom.constant = height;
}

- (void)keyboardWillHide:(NSNotification *)notification {
   _listbottom.constant = 0;
}

//完成按钮后的操作
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchField resignFirstResponder];
}

//根据关键字或者列表
-(NSMutableArray *)searchGroupList:(NSString *)searchkey
{
    NSMutableArray * orgArray = [[NSMutableArray alloc] init];
    if([searchkey isEqualToString:@""])
        return  orgArray;
    
   //需要对数据进行剔重20151010
    NSString *swheresql = [NSString stringWithFormat:@"SELECT *,count(distinct id) from contacts where operate='U' and name like '%%%@%%' group by id ",searchkey];
    NSMutableArray *allList  = [[NSMutableArray alloc] initWithArray:[ContactDao getDistinctContactByWhere:swheresql]];
    
    //过滤用户
    NSPredicate *predicateUsers = [NSPredicate predicateWithFormat:@"mTYPE != %@",@"O"];
    NSArray *usersList = [allList filteredArrayUsingPredicate:predicateUsers];
    NSMutableDictionary *userData = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                     @"用户", @"name", usersList, @"list", nil];
    if(usersList.count>0)
        [orgArray addObject:userData];
    //过滤机构
    NSPredicate *predicateOrg = [NSPredicate predicateWithFormat:@"mTYPE==%@",@"O"];
    NSArray *orgsList = [allList filteredArrayUsingPredicate:predicateOrg];
    NSMutableDictionary *orgsData = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                     @"群组", @"name", orgsList, @"list", nil];
    if(orgsList.count>0)
        [orgArray addObject:orgsData];
    
    return orgArray;
}

//列表组
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
     return searchArr.count;
}
//指定标题的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 30;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.001;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSMutableArray *arraysection = [[searchArr objectAtIndex:section] objectForKey:@"list"];
    return arraysection.count;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    Contact *contact =[[[searchArr objectAtIndex:indexPath.section] objectForKey:@"list"] objectAtIndex:indexPath.row];
    if([contact.mTYPE isEqualToString:@"O"])//机构
    {
        //选择的单元格信息
        selectTableViewController * selectTable = [[selectTableViewController alloc] init];
        selectTable.curOrgContact = contact;
        selectTable.CreateType = CreateType;
        selectTable.selectedContact = selectedContact;
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:selectTable animated:YES];
    }
    else //个人
    {
        BOOL isFind = NO;
        for (Contact * i   in  selectedContact)
        {
            if ([i.mID isEqualToString:contact.mID]) {
                [selectedContact removeObject:i];
                [_grpMemberList removeUnit:contact];
                isFind = YES;
                break;
            }
        }
        
        if (!isFind) {
            [selectedContact addObject:contact];
            [_grpMemberList addNewUnit:contact];
        }
        
        
        NSArray *indexArray=[NSArray arrayWithObject:indexPath];
        [_tablegrpmember reloadRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * CellIdentifier = @"selectMemberTableViewCell";
    selectMemberTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(!cell)
    {
        cell = [[[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil] objectAtIndex:0];
    }
    Contact *contact =[[[searchArr objectAtIndex:indexPath.section] objectForKey:@"list"] objectAtIndex:indexPath.row];
    //用户
    if(![contact.mTYPE isEqualToString:@"O"])
    {
        cell.titleLabel.font = [UIFont systemFontOfSize:15];
        cell.detailLabel.font = [UIFont systemFontOfSize:12];
        cell.detailLabel.textColor = [UIColor colorWithRed:85.0f/255.0f green:85.0f/255.0f blue:85.0f/255.0f alpha:1.0f];
        cell.detailLabel.textAlignment = NSTextAlignmentRight;
        [cell setContactSelected:[self containsContact:selectedContact contact:contact]];
        [cell setSelectMemberTableViewCell:contact];
    }
    else //群组
    {
        //头像
        NSURL *url= [NSURL URLWithString: [contact.mHEAD_IMG hasPrefix:@"http"]?contact.mHEAD_IMG:[NSString stringWithFormat:@"%@%@",DE.fileEngineeUrl,contact.mHEAD_IMG]];
        [cell.headImage setImageWithURL:url placeholderImage:[UIImage imageNamed:@"empty_photo"]];
        cell.titleLabel.text = contact.mNAME;
        cell.titleLabel.font = [UIFont systemFontOfSize:13];
        cell.checkBox.hidden = YES;
        cell.imagexconstraint.constant = -18;
        cell.detailLabel.hidden = YES;
    }
    
    return cell;
}

- (BOOL)containsContact:(NSMutableSet*) set contact:(Contact *)contact
{
    for (Contact * i   in  set)
    {
        if ([i.mID isEqualToString:contact.mID]) {
            return YES;
        }
    }
    return NO;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}



- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if(searchArr.count==0)
        return @"";
    else
        return [[searchArr objectAtIndex:section] objectForKey:@"name"];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// called when text changes (including clear)
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    NSLog(@".....%@",searchText);
    searchArr = [self searchGroupList:searchText];
    [_tablegrpmember reloadData];
    
}
// called when cancel button pressed
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    NSLog(@"取消");
   /* kAppDelegate.needRefrsh=YES;
    [kAppDelegate.iCSDrawerController.navigationController popToRootViewControllerAnimated:YES];*/
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    //刷新(选择了群成员之后返回本级页面时需要刷新下成员列表)
    //先清空所有的
    [_grpMemberList removeAll];
    //重新展示列表
    for( Contact * contact in selectedContact)
    {
        [_grpMemberList addNewUnit:contact];
    }
}

//点击事件（点击即从已选列表中删除）
- (void) extendCellTouched:(UnitCell *)unitCell
{
    //点击选择好的成员后，需要清理数据
    Contact *contact =unitCell.contact;
    
    for (Contact * i   in  selectedContact)
    {
        if ([i.mID isEqualToString:contact.mID]) {
            [selectedContact removeObject:i];
            [_tablegrpmember reloadData];
            break;
        }
    }
}

- (void) unitDoneTouched:(id)sender
{   //返回上一级
   /*[kAppDelegate.iCSDrawerController.navigationController popViewControllerAnimated:YES];*/
    NSLog(@"点击完成按钮**************************");
    [searchField resignFirstResponder];
    //直接跳转到群资料那个页面
    if([CreateType isEqualToString:CREATETYPE_ADDGROUP])
    {
        for (UIViewController *temp in kAppDelegate.iCSDrawerController.navigationController.viewControllers) {
            if ([temp isKindOfClass:[GroupInfoViewController class]]) {
                [kAppDelegate.iCSDrawerController.navigationController popToViewController:temp animated:YES];
            }
        }
    }else if ([CreateType isEqualToString:CREATETYPE_CREATECHAT])
    {
        //创建讨论组
        if(selectedContact.count >200 || selectedContact.count <2)
        {
            [self showAlerHUD:@"添加的成员人数不能小于2人和大于200人"];
            return;
        }
        
        /*"groupType":"1", --群组类型1 普通群 2 行政群 3 讨论组
         "userIds":"9004,9005,9006",--添加的用户列表，用逗号隔开 选填
         "groupName":"信网中心群",--群名称 选填
         "groupTags":"72,73,81",--群标签，多个值用逗号隔开 选填
         "toMountGroupId":"10000736",--挂靠的群组Id选填*/
        
        NSEnumerator *enumerator = [selectedContact objectEnumerator];
        NSMutableString *ids = [[NSMutableString alloc] initWithString:@""];
        [ids insertString:[NSString stringWithFormat:@"%@,",DE.userId] atIndex:0];
        for (Contact *cid in enumerator) {
            [ids insertString:[NSString stringWithFormat:@"%@,",cid.mID] atIndex:0];
        }
        
        NSDictionary *dict  = @{@"groupType":@"3",
                                @"userIds":ids,
                                @"groupName":@"",
                                @"groupTags":@"",
                                @"toMountGroupId":@""};
        
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [DE serverCall:@"createGrp" params:dict callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
            
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
            if (success) {
                NSString *addVersion = [DE getGlobalVar:[NSString stringWithFormat:@"%@_%@", [DE getGlobalVar:LOGIN_USER_REALID],[DE getGlobalVar:CONTACT_VERSION]]];
                NSDictionary *userInfo = @{@"AddressBookVersion":addVersion==nil?@"0":addVersion};
                
                [DE serverCall:@"refreshAdBook" params:userInfo callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
                    
                    if(success){
                        @try {
                            [DE updateLocalDBContacts:[data objectForKey:@"txl"] sessionId:nil businessId:nil sendout:YES];
                            UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"提示" message:@"创建成功！" delegate:self cancelButtonTitle:@"返回上一级" otherButtonTitles:nil, nil];
                            [view show];
                        }
                        @catch (NSException *exception) {
                            [self showAlerHUD:@"创建讨论组失败！"];
                        }
                        
                    }else{
                        [self showAlerHUD:@"创建讨论组失败！"];
                        
                    }
                    
                }];
                
            }else{
                UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"提示" message:@"创建失败！" delegate:self cancelButtonTitle:@"返回上一级" otherButtonTitles:@"确定", nil];
                [view show];
            }
            
        }];
    }
    else if([CreateType isEqualToString:CREATETYPE_CREATEGROUP])
    {
        NSLog(@"点击选择成员完成");
        for (UIViewController *temp in kAppDelegate.iCSDrawerController.navigationController.viewControllers) {
            if ([temp isKindOfClass:[CreateGroupViewController class]]) {
                [kAppDelegate.iCSDrawerController.navigationController popToViewController:temp animated:YES];
            }
        }
    }

}
    


//重写提示效果(个性化)
-(void)showAlerHUD:(NSString*)text
{
    BDKNotifyHUD * hudex = [[BDKNotifyHUD alloc] initWithImage:[UIImage imageNamed:@""]  text:text];
    hudex.center = CGPointMake(self.view.center.x, self.view.center.x);
    [self.view addSubview:hudex];
    [hudex presentWithDuration:1.5 speed:0.5f inView:self.view completion:^{
        [hudex removeFromSuperview];
    }];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==0) {
        kAppDelegate.needRefrsh = YES;
        [kAppDelegate.iCSDrawerController.navigationController popToRootViewControllerAnimated:NO];
    }
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
